<template>
  <ZWDrawer ref="DetailRef"
    ><div class="contents"><ZwSearchForm row-num="2" :option="searchOption" @search="search" @reset="reset" /> <ZwTable ref="tableRef" class="table-box" :option="tableOption" :fetch-params="state.searchParams" :fetch-api="fetch()"> </ZwTable></div
  ></ZWDrawer>
  <!-- 任务凭证 -->
  <Dialog :appDialog="commit ? appDialog : conDialog"
    ><div class="dialog"
      ><div class="tips" v-if="showtips">{{ tips }}</div>
      <div
        ><div class="detail">推送内容：{{ getText }}</div
        ><div>SOP周期：{{ gettime }}</div></div
      >
      <el-form :form="listData">
        <el-form-item label="上传凭证" required
          ><br /><div v-if="listData.corporate_times"
            ><div>上传企微客户朋友圈凭证（每日客户仅收到{{ listData.corporate_times }}篇）</div
            ><div v-if="!commit"
              ><template v-for="(item, index) in listData.voucher_corporate_list" :key="index"><el-image style="width: 100px; height: 100px; margin: 0 8px 8px 0" :src="item.file_url" :preview-src-list="[item.file_url]" :preview-teleported="true"> </el-image></template></div
            ><div v-if="commit" class="space">
              <div v-for="(item, index) in getpram.voucher_corporate_list" :key="index" class="item">
                <span class="icondelete">
                  <el-icon @click="del(item.id, index, getpram.voucher_corporate_list)" class="iconimg"><delete /></el-icon>
                </span>
                <el-image :src="item.file_url" :preview-src-list="[item.file_url]" :preview-teleported="true" class="elimage"> </el-image>
              </div>
              <el-upload ref="elupload" action="#" list-type="picture-card" :auto-upload="false" :limit="listData.corporate_times" accept=".png,.jpg,.jpeg" :on-change="handleChange" :class="{ hide: hideUpload }" style="display: inline">
                <template #default>
                  <el-icon><plus /></el-icon>
                </template>
                <template #file="{ file }">
                  <el-image style="el-upload-list__item-actions" :src="file.url"></el-image>
                  <div>
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <el-icon><delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload> </div></div
          ><div v-if="listData.personal_times"
            ><div>上传个人微信朋友圈凭证（每日客户仅收到{{ listData.personal_times }}篇）</div>
            <div v-if="!commit"
              ><template v-for="(item, index) in listData.personal_corporate_list" :key="index"><el-image style="width: 100px; height: 100px; margin: 0 8px 8px 0" :src="item.file_url" :preview-src-list="[item.file_url]" :preview-teleported="true"> </el-image></template
            ></div>
            <div v-if="commit" class="space">
              <div v-for="(item, index) in getpram.personal_corporate_list" :key="index" class="item">
                <span class="icondelete"
                  >{{ index }}
                  <el-icon @click="del(item.id, index, getpram.personal_corporate_list)" class="iconimg"><delete /></el-icon>
                </span>
                <el-image :src="item.file_url" :preview-src-list="[item.file_url]" :preview-teleported="true" class="elimage"> </el-image>
              </div>
              <el-upload ref="perelupload" action="#" list-type="picture-card" :auto-upload="false" :limit="listData.personal_times" accept=".png,.jpg,.jpeg" :on-change="Change" :class="{ hide: hidepersonUpload }" style="display: inline">
                <template #default>
                  <el-icon><plus /></el-icon>
                </template>
                <template #file="{ file }">
                  <el-image style="el-upload-list__item-actions" :src="file.url"></el-image>
                  <div>
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="Remove(file)">
                        <el-icon><delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template> </el-upload
            ></div> </div
        ></el-form-item>
        <el-form-item label="备注"><el-input type="textarea" rows="4" resize="none" v-model="listData.remark" :disabled="!commit" show-word-limit maxlength="100"></el-input> </el-form-item>
      </el-form> </div
  ></Dialog>
  <!-- 不达标弹窗 -->
  <Dialog :appDialog="passDialog"
    ><el-form :form="passData"
      ><el-form-item label="原因"><el-input v-model="passData.msg" type="textarea" rows="6" resize="none"></el-input></el-form-item></el-form
  ></Dialog>
</template>
<script lang="tsx" setup>
  import { ref, reactive, computed } from 'vue'
  import { ElButton, ElMessage } from 'element-plus'
  import type { UploadFile } from 'element-plus/es/components/upload/src/upload'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'
  import ZwTable from '@/components/zw/table/Table'
  import ZWDrawer from '@/components/ZWDrawer.vue'
  import Dialog from '@/components/Dialog.vue'
  import { deepCopy } from '@/utils/helper'
  import { uploadFile2 } from '@/api/common'
  import { IsNotEmpty, getImage_wh } from '@/utils/utils'
  import { getsopList, memberList, alart, targetDetail, submitTarget, pass } from '@/api/smartMarketing/marketAutomation/friendCircleSop'
  const DetailRef = ref(null)
  const tableRef = ref(null)
  const rowid = ref(null) //凭证id
  const qa_enable = ref(null)
  const showtips = ref(true) //是否显示提示语
  const passData = reactive({ msg: '', pass: 1, work_user_job_id: '' })
  const id = ref('')
  const defaultParams = {}
  const tips = ref('')
  const elupload = ref(null)
  const perelupload = ref(null)
  const delids = ref([]) //记录删除图片的凭证id
  const state = reactive({
    searchParams: deepCopy(defaultParams)
  })
  const commit = ref(true) //区分上传凭证or质检凭证
  let getpram = reactive({})
  const listData = reactive({
    corporate_times: 0, //企微朋友圈数量
    personal_times: 0, //个微朋友圈数量
    cycle_type: 1, //1 日 2 周 3 月
    start_time: '', //开始时间
    end_time: '',
    voucher_corporate_list: [],
    personal_corporate_list: [],
    remark: ''
  })
  const getText = computed(() => {
    var detailText: any = []
    if (listData.personal_times != 0) {
      detailText.push(listData.personal_times + '篇个人微信朋友圈')
    }
    if (listData.corporate_times != 0) {
      detailText.push(listData.corporate_times + '篇企业微信朋友圈')
    }
    return detailText.join('、')
  })
  const hideUpload = computed(() => {
    return listData.corporate_times <= listData.voucher_corporate_list.length
  })
  const hidepersonUpload = computed(() => {
    return listData.personal_times <= listData.personal_corporate_list.length
  })
  const gettime = computed(() => {
    if (listData.cycle_type == 1) {
      return '每日（' + listData.start_time.substr(0, 10) + '）'
    }
    if (listData.cycle_type == 2) {
      return '每周（' + getWeek(listData.start_time.substr(0, 10)) + '）'
    }
    if (listData.cycle_type == 3) {
      return '每月（' + listData.start_time.substr(0, 7) + '）'
    }
  })
  const getWeek = (date: any) => {
    date = new Date(date)
    var date2 = new Date(date.getFullYear(), 0, 1)
    var day1 = date.getDay()
    if (day1 == 0) day1 = 7
    var day2 = date2.getDay()
    if (day2 == 0) day2 = 7
    let d = Math.round((date.getTime() - date2.getTime() + (day2 - day1) * (24 * 60 * 60 * 1000)) / 86400000)
    //当周数大于52则为下一年的第一周
    if (Math.ceil(d / 7) + 1 > 52) {
      return date.getFullYear() + 1 + '第1周'
    }
    return date.getFullYear() + ' 第' + (Math.ceil(d / 7) + 1) + '周'
  }

  const cancelHandel = () => {
    appDialog.visible = false
  }
  const passcancel = () => {
    pass({
      work_user_job_id: rowid.value,
      pass: 2,
      msg: passData.msg
    }).then((res: any) => {
      ElMessage.success('质检成功')
      tableRef.value.reload()
      passDialog.visible = false
      conDialog.visible = false
    })
  }
  const submitHandel = () => {
    if (appDialog.submitText == '我已完成，提交凭证') {
      var param = JSON.parse(JSON.stringify(listData))
      for (let key in param) {
        if (key == 'personal_corporate_list' || key == 'voucher_corporate_list') {
          param[key].forEach((item: any) => {
            delete item.name
            delete item.url
            delete item.uid
          })
        }
      }
      var sendparam: any = { complete: true, personal_corporate_list: param.personal_corporate_list, voucher_corporate_list: param.voucher_corporate_list, work_user_job_id: rowid.value, remark: param.remark }
      if (delids.value.length) {
        sendparam.delete_voucher_list = delids.value
      }
      submitTarget(sendparam).then((res: any) => {
        ElMessage.success('上传成功')
        tableRef.value.reload()
        appDialog.visible = false
      })
    } else {
    }
  }
  const appDialog = reactive({
    visible: false,
    title: `上传任务凭证`,
    width: '700px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
  })
  const nopassHandel = () => {
    passDialog.visible = true
  }
  const passHandel = () => {
    pass({
      work_user_job_id: rowid.value,
      pass: 1,
      msg: ''
    }).then((res: any) => {
      ElMessage.success('质检成功')
      tableRef.value.reload()
      conDialog.visible = false
    })
  }
  const conDialog = reactive({
    visible: false,
    title: `上传任务凭证`,
    width: '700px',
    moreBtn: nopassHandel,
    submit: passHandel,
    moreBtnText: '不达标',
    submitText: '达标'
  })
  const passDialog = reactive({
    visible: false,
    title: `质检不达标`,
    width: '700px',
    submit: passcancel,
    submitText: '不达标'
  })
  const searchOption = computed(() => {
    return [
      {
        label: '执行人',
        name: 'work_user_list',
        value: [],
        type: 'select',
        placeholder: '全部',
        multiple: true,
        popperClass: 'zw-hide_select_option',
        isUserSelect: true,
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      }
    ]
  })
  const coloum = ref([
    {
      prop: 'check_status',
      label: '质检情况',
      width: 120,
      render({ row }) {
        return row.check_status == 0 ? '未质检' : row.check_status == 1 ? '已达标' : '未达标'
      }
    },
    {
      prop: 'qa_at',
      label: '质检时间',
      width: 200
    }
  ])
  const tableOption = [
    {
      prop: 'work_user_name',
      label: '执行人',
      width: 120
    },
    {
      prop: 'commit_status',
      label: '完成情况',
      width: 120,
      render({ row }) {
        return row.commit_status == 0 ? '未完成' : '已完成'
      }
    },
    {
      prop: 'complete_at',
      label: '完成时间',
      width: 200
    },
    {
      prop: 'check_status',
      label: '质检情况',
      width: 120,
      render({ row }) {
        return row.check_status == 0 ? '未质检' : row.check_status == 1 ? '已达标' : '未达标'
      }
    },
    {
      prop: 'qa_at',
      label: '质检时间',
      width: 200
    },
    {
      prop: 'operate',
      label: '操作',
      width: 200,
      fixed: 'right',
      isOperate: true,
      renderOperate({ row }) {
        return onBtn(row)
      }
    }
  ]
  const onBtn = (row: any) => {
    if (row.allow_complate == 1 && row.commit_status == 0) {
      //登录账号是本人并且没有提交完成凭证
      return (
        <>
          <ElButton size="small" onClick={() => sopBtn(row, 3)}>
            提醒
          </ElButton>
          <ElButton size="small" onClick={() => sopBtn(row, 4)}>
            完成
          </ElButton>
        </>
      )
    } else if (row.commit_status == 0) {
      // 没有提交上传凭证
      return (
        <>
          <ElButton size="small" onClick={() => sopBtn(row, 3)}>
            提醒
          </ElButton>
        </>
      )
    } else if (row.allow_complate == 1 && row.check_status == 2 && row.allow_check == 1) {
      //上传后被打回重新上传凭证
      return (
        <>
          <ElButton size="small" onClick={() => sopBtn(row, 5)}>
            完成
          </ElButton>
        </>
      )
    } else if (row.allow_check == 1 && row.check_status == 2 && row.allow_complate == 0) {
      return (
        <>
          <ElButton size="small" onClick={() => sopBtn(row, 2)}>
            重新质检
          </ElButton>
        </>
      )
    } else if (row.allow_check == 1 && row.check_status == 0 && row.commit_status == 1) {
      return (
        <>
          <ElButton size="small" onClick={() => sopBtn(row, 1)}>
            质检
          </ElButton>
        </>
      )
    }
  }
  const openPass = (row: any) => {
    showtips.value = false
    targetDetail({ work_user_job_id: row.id })
      .then((res: any) => {
        Object.assign(listData, res)
      })
      .catch((err: any) => {
        ElMessage.error(err)
      })
    conDialog.visible = true
    conDialog.title = row.work_user_name + '【客户SOP名称】任务质检'
  }
  const sopBtn = (row: any, num: any) => {
    switch (num) {
      case 1:
        rowid.value = row.id
        commit.value = false
        openPass(row)
        break
      case 2:
        rowid.value = row.id
        commit.value = false
        openPass(row)
        break
      case 3:
        rowid.value = row.id
        alart({ work_user_job_id: row.id })
          .then((res: any) => {
            ElMessage.success('提醒成功')
          })
          .catch((e: any) => {
            ElMessage.error('提醒失败')
          })

        break
      case 4:
        send(row)
        break
      case 5:
        send(row)
        break
    }
  }
  const send = (row: any) => {
    commit.value = true
    rowid.value = row.id
    delids.value = []
    targetDetail({ work_user_job_id: row.id })
      .then((res: any) => {
        Object.assign(listData, res)
        listData.voucher_corporate_list = []
        listData.personal_corporate_list = []
        var data: any = JSON.parse(JSON.stringify(res))
        Object.assign(getpram, data)
      })
      .catch((err: any) => {
        ElMessage.error(err)
      })
    tips.value = qa_enable.value == 1 ? '您已发送朋友圈，请提交发送凭证，待质检人确认是否真实完成。若您不提交凭证，将视为无按照要求完成，显示【未达标】' : '您已发送朋友圈，请提交发送凭证'
    appDialog.visible = true
    appDialog.cancelText = '取消'
    appDialog.submitText = '我已完成，提交凭证'
    appDialog.title = '上传' + row.work_user_name + '的任务凭证'
  }
  //查询
  const search = (v) => {
    state.searchParams = v
  }
  const reset = (v) => {
    state.searchParams = deepCopy(defaultParams)
  }
  const getids = () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(id.value)
      }, 1)
    })
  }
  const fetch = async () => {
    const id = await getids()
    return [{ id }, memberList]
  }

  // 判断是否有质检人(没有质检人会去除质检人和质检时间这两列)
  const getparam = () => {
    if (!qa_enable.value && tableOption.length == 6) {
      tableOption.splice(3, 2)
    }
    if (qa_enable.value && tableOption.length < 6) {
      tableOption.splice(5, 0, coloum.value[0], coloum.value[1])
    }
  }
  const open = (title: any) => {
    getparam()
    DetailRef.value.drawer = true
    DetailRef.value.isShow = false
    DetailRef.value.width = 700
    DetailRef.value.title = `【${title}】完成情况`
  }
  const handleRemove = async (file: UploadFile) => {
    listData.voucher_corporate_list = listData.voucher_corporate_list.filter((item: any) => {
      return item.uid !== file.uid
    })
    elupload.value.handleRemove(file)
  }
  const Remove = async (file: UploadFile) => {
    listData.personal_corporate_list = listData.personal_corporate_list.filter((item: any) => {
      return item.uid !== file.uid
    })
    perelupload.value.handleRemove(file)
  }
  const beforeUpdata = async (file: any, type: any) => {
    const is2M = file.size / 1024 / 1024 <= 10
    const { W, H } = await getImage_wh(file)
    let ext = file.name.substring(file.name.lastIndexOf('.'))
    if ('.png,.jpg,.jpeg'.indexOf(ext) == -1) {
      ElMessage.warning(`该图片是${ext}格式,请上传.png,.jpg,.jpeg格式图片`)
      handleRemove(file)
      return
    }
    if (W > 1440) {
      ElMessage.warning(`该图片宽度${W}px,超过最大图片尺寸宽度1440px`)
      type == 1 ? handleRemove(file) : Remove(file)
      return
    }
    if (H > 1080) {
      ElMessage.warning(`该图片高度${H}px,超过最大图片尺寸高度1080px`)
      type == 1 ? handleRemove(file) : Remove(file)
      return
    }
    if (!is2M) {
      ElMessage.warning(`上传的图片最大支持10M`)
      type == 1 ? handleRemove(file) : Remove(file)
      return
    }
    return is2M && W <= 1440 && H <= 1080
  }
  // 上传文件
  const uploadImg = async (file: any, num: any) => {
    file = file.raw
    let flag = beforeUpdata(file, num)
    if (!flag) return
    return await uploadFile2({
      file,
      fileName: file.name
    })
  }
  const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    const data: any = await uploadImg(file, 1)
    if (IsNotEmpty(data)) {
      listData.voucher_corporate_list.push({ ...data, uid: file.uid })
    }
  }
  const Change = async (file: UploadFile, list: UploadFile[]) => {
    const data: any = await uploadImg(file, 2)
    if (IsNotEmpty(data)) {
      listData.personal_corporate_list.push({ ...data, uid: file.uid })
    }
  }
  const del = (ids: any, index: any, data: any) => {
    delids.value.push(ids)
    data.splice(index, 1)
  }
  defineExpose({ open, qa_enable, id })
</script>
<style lang="scss" scoped>
  .hide {
    :deep .el-upload {
      display: none;
    }
  }
  .contents {
    padding: 20px 20px 10px 20px;
  }
  .dialog {
    .tips {
      margin-bottom: 24px;
      padding: 9px 16px 9px 12px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      line-height: 22px;
      background: #fffbe6;
      border-radius: 2px;
      border: 1px solid #ffe58f;
    }
    .detail {
      margin-bottom: 10px;
    }
    .space {
      .item:hover .icondelete {
        display: block;
      }
      .item {
        display: inline-block;
        position: relative;
        border: 1px solid #c0ccda;
        border-radius: 6px;
        box-sizing: border-box;
        width: 148px;
        height: 148px;
        overflow: hidden;
        margin: 0 8px 8px 0;
        .elimage {
          overflow: none;
        }
        .icondelete {
          position: absolute;
          display: none;
          width: 148px;
          height: 148px;
          z-index: 999;
          font-size: 20px;
          color: #fff;
          border-radius: 6px;
          background-color: rgba(0, 0, 0, 0.5);
          .iconimg {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            cursor: pointer;
          }
        }
      }
    }
  }
</style>
